package fiuba.descuentos;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.MapView.LayoutParams;

import Entities.Benefit;
import Helpers.ContextHelper;
import Listeners.CustomLocationListener;
import Service.Parameter;
import Service.WellKnownKeys;
import Service.WellKnownMethods;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class Map extends MapBase {
	MapView mapView;
	MapController mc;
	private ArrayList<Benefit> benefits;	
	
	int minLatitude = Integer.MAX_VALUE;
    int maxLatitude = Integer.MIN_VALUE;
    int minLongitude = Integer.MAX_VALUE;
    int maxLongitude = Integer.MIN_VALUE;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
        
        Vector props = new Vector();
		Parameter categoryId = new Parameter(WellKnownKeys.CategoryIdKey,-1);
		props.add(categoryId);
		
		callService(WellKnownMethods.GetBenefitsByCategory, props);
    }         
    
    @Override
	public void onServiceCompleted(JSONObject obj, String method) {
		if (WellKnownMethods.GetBenefitsByCategory.compareTo(method) == 0){
			onGetBenefitsCompleted(obj);
		}
	}

	private void onGetBenefitsCompleted(JSONObject obj) {
		boolean resultSuccess;
		hideLoading();
		try {
			resultSuccess = obj.getBoolean("success");
			if (resultSuccess) {
				this.benefits = Benefit.getFromJSON(obj);
				bindItems();
			}else{
				showErrorMessage(obj.getString("message"));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}				
	}
	
	private void bindItems(){
		
		mapView = (MapView) findViewById(R.id.mapView);
        mapView.setBuiltInZoomControls(true);
        
        mc = mapView.getController();
        Location loc = CustomLocationListener.getCurrentLocation();
        List<Overlay> listOfOverlays = mapView.getOverlays();
        listOfOverlays.clear();
        GeoPoint p;
        if (loc != null){
        	
	        p = new GeoPoint(
	            (int) (loc.getLatitude() * 1e6), 
	            (int) (loc.getLongitude() * 1e6));
	        
	        maxLatitude = p.getLatitudeE6();
	        minLatitude = p.getLatitudeE6();
	        maxLongitude = p.getLongitudeE6();
	        minLongitude = p.getLongitudeE6();
	        Drawable mydrawable = this.getResources().getDrawable(R.drawable.mymarker);
	        CustomItemizedOverlay itemizedoverlay = new CustomItemizedOverlay(mydrawable);
	        OverlayItem overlayitem = new OverlayItem(p, "estoy aqui", "");

	        itemizedoverlay.addOverlay(overlayitem, null);
	        listOfOverlays.add(itemizedoverlay);	        
        }
         
                
        Drawable markerdrawable = this.getResources().getDrawable(R.drawable.marker);
        CustomItemizedOverlay itemizedoverlay2 = new CustomItemizedOverlay(markerdrawable);
        
        
        // Find the boundaries of the item set
        for (Benefit item : this.benefits) { 
	        int lat = (int)(item.getLatitude() * 1e6);
	        int lon = (int)(item.getLongitude() * 1e6);
	
	        maxLatitude = Math.max(lat, maxLatitude);
	        minLatitude = Math.min(lat, minLatitude);
	        maxLongitude = Math.max(lon, maxLongitude);
	        minLongitude = Math.min(lon, minLongitude);
	        
	        p = new GeoPoint(lat, lon);
	        
	        OverlayItem overlayitem = new OverlayItem(p, item.getName(), item.getDescription());
	        itemizedoverlay2.addOverlay(overlayitem, item);	        	      
         }
        
        listOfOverlays.add(itemizedoverlay2);
        
         mc.zoomToSpan(Math.abs(maxLatitude - minLatitude), Math.abs(maxLongitude - minLongitude));
         mc.setCenter(new GeoPoint( 
        		 (maxLatitude + minLatitude)/2, 
        		 (maxLongitude + minLongitude)/2 ));
         mapView.invalidate();
	}
	
	public class CustomItemizedOverlay extends ItemizedOverlay {

	    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    	View popUp;
    	private ArrayList<Benefit> benefits = new ArrayList<Benefit>();


	    public CustomItemizedOverlay(Drawable defaultMarker) {
	        super(boundCenterBottom(defaultMarker));	       
	    }

	    public void addOverlay(OverlayItem overlay, Benefit benefit) {

	        mOverlays.add(overlay);
	        benefits.add(benefit);
	        populate();
	    }
	    
	    @Override
	    protected OverlayItem createItem(int i) {
	        // TODO Auto-generated method stub
	        return mOverlays.get(i);
	    }

	    @Override
	    public int size() {
	        // TODO Auto-generated method stub
	        return mOverlays.size();
	    }

	    @Override
	    protected boolean onTap(int index) {
	        OverlayItem item = mOverlays.get(index);
	        
	        MapView.LayoutParams mapParams = new MapView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    item.getPoint(), MapView.LayoutParams.BOTTOM_CENTER);

	        try{
	        	mapView.removeView(popUp);
	        }catch(Exception e){	        		        
	        }
			
			popUp = getLayoutInflater().inflate(R.layout.map_popup, mapView, false);
			
			TextView name = (TextView) popUp.findViewById(R.id.name);
			name.setText(item.getTitle());
			final Benefit benefit = this.benefits.get(index);
			if (benefit != null){
				name.setOnClickListener(new OnClickListener() {
			        public void onClick(View v) {
			        	Intent intent = new Intent(ContextHelper.getContextInstance(), BenefitDetail.class);
			        	intent.putExtra("benefit", benefit);
			        	startActivity(intent);
			        }
			    });
			}	
			
			
			TextView description = (TextView) popUp.findViewById(R.id.description);
			description.setText(item.getSnippet());
			
			ImageView close = (ImageView) popUp.findViewById(R.id.close_img_button);
			
			close.setOnClickListener(new OnClickListener() {
		        public void onClick(View v) {
		        	mapView.removeView(popUp);
		        }
		    });
			

			mapView.addView(popUp, mapParams);
	        
	        return true;
	    }

	}          
}